package cn.uce.cc.srv.biz.impl;

import cn.uce.base.ccos.RoutTrackVo;
import cn.uce.base.ccos.VaInfoVo;
import cn.uce.base.entity.CcSmsRecord;
import cn.uce.base.vo.CcSmsRecordVo;
import cn.uce.cc.api.service.biz.ICcSmsMessageBiz;
import cn.uce.cc.api.service.biz.ICcosRoutTrackBiz;
import cn.uce.cc.api.service.biz.ICcosWaybillBiz;
import cn.uce.cc.srv.service.CcSmsMessageService;
import cn.uce.common.constants.CcConstants;
import cn.uce.common.omg.biz.IOmgOrgBiz;
import cn.uce.mcs.base.vo.ReceiverRangeMobileVo;
import cn.uce.mcs.caller.api.vo.MessageReqVo;
import cn.uce.mcs.caller.api.vo.MessageRespVo;
import cn.uce.mcs.caller.sdk.CallerHelper;
import cn.uce.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;


/**
 * 发送短信功能
 */
@Service
@Transactional(readOnly = true, propagation= Propagation.SUPPORTS, rollbackFor = Exception.class)
public class CcSmsMessageBiz implements ICcSmsMessageBiz {
    private static final Logger log = LoggerFactory.getLogger(CcSmsMessageBiz.class);
    @Resource
    private CcSmsMessageService  ccSmsMessageService;

    @Autowired
    private CallerHelper callerHelper;


    @Resource
    private IOmgOrgBiz omgOrgBiz;


    @Resource
    private ICcosWaybillBiz ccosWaybillBiz;
    
    @Resource
    private ICcosRoutTrackBiz ccosRoutTrackBiz;
    
    /**
     *
     * @param ccSmsRecord
     * @return
     */
    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public CcSmsRecord sendMessage(CcSmsRecord ccSmsRecord) {
        ccSmsMessageService.addCsSmsRecordxReturnId(ccSmsRecord);
        log.info("message.sendMessage-begin"+ JSON.toJSONString(ccSmsRecord));
        if(ccSmsRecord != null && StringUtil.isNotBlank(ccSmsRecord.getMoblileNum()) && ccSmsRecord.getMoblileNum().contains("*")){
            return  null;
        }
        MessageReqVo messageReqVo = setMessageReqVo(ccSmsRecord);
        log.info("message.sendMessage-setMessageReqVo"+ JSON.toJSONString(messageReqVo));
        MessageRespVo messageRespVo = null;
        if (messageReqVo != null){
            try {
                messageRespVo = callerHelper.sendMessage(messageReqVo);
                log.info("message.sendMessage-end"+ JSON.toJSONString(messageRespVo));
                ccSmsRecord.setResultCode(messageRespVo.getReturnCode());
                ccSmsRecord.setReqId(messageRespVo.getReqId());
                ccSmsRecord.setResultMsg(messageRespVo.getReturnMsg());
            } catch (Exception e) {
                log.error("sendMessageException",e);
                ccSmsRecord.setResultCode("发送失败");
            }
        }
        log.info("sendMessage,return:"+ JSON.toJSONString(ccSmsRecord));
        ccSmsMessageService.updateById(ccSmsRecord);
        return ccSmsRecord;
    }

    @Override
    public CcSmsRecord findBillCodeAndPhoneNum(CcSmsRecordVo queryVo) {
        return  ccSmsMessageService.findBillCodeAndPhoneNum(queryVo);
    }

    /**
     *
     * @param sendPhone
     * @param sendType 1 代收货款  2 货物路由  3 下单
     * @param wayNum
     * @return
     */
    @Override
    public String sendMessageByYunhu(String sendPhone, String sendType, String wayNum) {
        if (StringUtil.isNotBlank(sendPhone) && StringUtil.isNotBlank(sendType)){
            CcSmsRecord ccSmsRecord = new CcSmsRecord();
            ccSmsRecord.setCreateOrgCode(omgOrgBiz.getHqOrgCode());
            ccSmsRecord.setMoblileNum(sendPhone);
            ccSmsRecord.setPayOrgCode(omgOrgBiz.getHqOrgCode());
            ccSmsRecord.setCreateEmp("云呼");
            ccSmsRecord.setBillCode(wayNum);
            boolean flag = false;
            if (CcConstants.YUNHU_COD.equals(sendType)){
                //首先调用代收货款短信
                flag =  getCodMessage(ccSmsRecord);
            }
            if (CcConstants.YUNHU_QUERY_TRUNK.equals(sendType)){
                flag = getTrunkMessage(ccSmsRecord);
            }
            //下单短信
            if (CcConstants.YUNHU_ORDER.equals(sendType)){
            ccSmsRecord.setTemplateCode(CcConstants.CC_CREATE_ORDER);
            ccSmsRecord.setProblemTypeName(CcConstants.CC_CREATE_ORDER);
                flag = true;
            }
            if (flag){
                sendMessage(ccSmsRecord);
            }
        }
        return CcConstants.FAIL;
    }

    /**
     * 拼装物流轨迹短信
     * @param ccSmsRecord
     * @return
     */
    private boolean getTrunkMessage(CcSmsRecord ccSmsRecord) {
        if (ccSmsRecord == null || StringUtil.isBlank(ccSmsRecord.getBillCode())) {
            return false;
        }
        LinkedList<RoutTrackVo> routingLocusInfoByWBNo = ccosRoutTrackBiz.getRoutingLocusInfoByWBNo(ccSmsRecord.getBillCode());
        if (routingLocusInfoByWBNo != null && !routingLocusInfoByWBNo.isEmpty()){

            RoutTrackVo routTrackVo = routingLocusInfoByWBNo.get(0);
//            运单号为wayNum，context，感谢使用壹米滴答服务热线95058
            String deptName = routTrackVo.getOperateDep();
            String currt = deptName.substring(deptName.indexOf("[")+1,deptName.indexOf("]"));
            ccSmsRecord.setContext("于"+routTrackVo.getOperateTime()+"在"+currt+routTrackVo.getOperateTypeName());
            if (StringUtil.isBlank(deptName) || StringUtil.isBlank(currt)){
                return  false;
            }

            return  true;
        }else{
            return false;
        }

    }

    /**
     * 您的单号为wayNum，无代收货款，具体请联系始发网点，感谢使用壹米滴答服务热线95058
     * 运单号为wayNum，代收货款money元，已于date转款至people，如果有疑问，请及时联系银行对账！感谢使用壹米滴答服务热线95058
     * 首先判断是否有代收货款短信
     * @param ccSmsRecord
     * @return
     */
    private boolean getCodMessage(CcSmsRecord ccSmsRecord) {
        if (ccSmsRecord == null || StringUtil.isBlank(ccSmsRecord.getBillCode())) {
            return false;
        }
        VaInfoVo vaInfoVo  = ccosWaybillBiz.getVaInfoVoByBillCode(ccSmsRecord.getBillCode());
        if (vaInfoVo == null){
            //设置短信内容为
            ccSmsRecord.setTemplateCode(CcConstants.CC_NO_COD);
            ccSmsRecord.setProblemTypeName(CcConstants.CC_NO_COD);
        }else{
            ccSmsRecord.setTemplateCode(CcConstants.CC_HAVE_COD);
            ccSmsRecord.setProblemTypeName(CcConstants.CC_HAVE_COD);
            Map<String, Object> stringObjectMap = ccosWaybillBiz.wayBillInfo(ccSmsRecord.getBillCode());
            if (stringObjectMap != null && stringObjectMap.get("vaInfoVo")!= null){
                VaInfoVo goodValue = (VaInfoVo) stringObjectMap.get("vaInfoVo");
                String proxyPay = goodValue.getProxyPay();
                String transMoneyTime = vaInfoVo.getTransMoneyTime();
                String payee = vaInfoVo.getPayee();
                if (StringUtil.isBlank(proxyPay) || StringUtil.isBlank(transMoneyTime)  || StringUtil.isBlank(payee) ){
                    return false;
                }
                ccSmsRecord.setExpandOne(proxyPay);
                ccSmsRecord.setExpandTwo(transMoneyTime);
                ccSmsRecord.setExpandThree(payee);
                return  true;
            }
        }
        return false;
    }


    /**
     * 设置短信请求参数
     * @param ccSmsRecord
     * @return
     */
    private MessageReqVo setMessageReqVo(CcSmsRecord ccSmsRecord) {
        MessageReqVo messageReqVo = new MessageReqVo();
        ReceiverRangeMobileVo receiverRangeMobileVo = new  ReceiverRangeMobileVo();
        List<String> monbileList = new ArrayList<>();
        monbileList.add(ccSmsRecord.getMoblileNum());
        receiverRangeMobileVo.setMobileList(monbileList);
        messageReqVo.setReceiveRange(receiverRangeMobileVo);
        messageReqVo.setCallerCode("CC");
        messageReqVo.setBizId("CC"+ ccSmsRecord.getId());
        messageReqVo.setChannelTypes("Sms");
        messageReqVo.setTemplateCode(ccSmsRecord.getTemplateCode());
        JSONObject msgParam = new JSONObject();
        if (StringUtil.isNotBlank(ccSmsRecord.getTemplateCode()) && ccSmsRecord.getTemplateCode().equals(CcConstants.TEMPLATE_CUSTOM_CALL)){
            msgParam.put("content", ccSmsRecord.getContext());
        }
        if (StringUtil.isNotBlank(ccSmsRecord.getTemplateCode()) && ccSmsRecord.getTemplateCode().equals(CcConstants.CC_COMMON)){
            msgParam.put("content", ccSmsRecord.getContext());
        }
        if (StringUtil.isNotBlank(ccSmsRecord.getTemplateCode()) && ccSmsRecord.getTemplateCode().equals(CcConstants.TEMPLATE_SATISFIED_MESSAGE)){
            msgParam.put("satisfied_message", ccSmsRecord.getContext());
        }
        if (StringUtil.isNotBlank(ccSmsRecord.getTemplateCode()) && ccSmsRecord.getTemplateCode().equals(CcConstants.CC_NO_COD)){
            msgParam.put("wayNum", ccSmsRecord.getBillCode());
        }
        if (StringUtil.isNotBlank(ccSmsRecord.getTemplateCode()) && ccSmsRecord.getTemplateCode().equals(CcConstants.CC_NO_COD)){
            msgParam.put("wayNum", ccSmsRecord.getBillCode());
            msgParam.put("money", ccSmsRecord.getExpandOne());
            msgParam.put("date", ccSmsRecord.getExpandTwo());
            msgParam.put("已于date转款至people", ccSmsRecord.getExpandThree());
            //运单号为wayNum，代收货款money元，已于date转款至people，如果有疑问，请及时联系银行对账！感谢使用壹米滴答服务热线95058
        }
        messageReqVo.setMsgParam(msgParam);
        messageReqVo.setReqEmp(ccSmsRecord.getCreateEmp());
        messageReqVo.setReqOrgCode(ccSmsRecord.getCreateOrgCode());
        messageReqVo.setPayOrgCode(ccSmsRecord.getPayOrgCode());
        return messageReqVo;
    }
}
